'use strict'

const Controller = require('egg').Controller

class AuthController extends Controller {

  constructor(ctx) {
    super(ctx)

    this.UserLoginTransfer = {
      username: { type: 'string', required: true, allowEmpty: false },
      password: { type: 'password', required: true, allowEmpty: false }
    }


    this.UserUpdatePassword = {
      password: { type: 'password', required: true, allowEmpty: false },
      new_password: { type: 'password', required: true, allowEmpty: false },
      new_password_confirmation: { type: 'password', required: true, allowEmpty: false, compare: 'new_password' },
    }

  }

  // 用户登入
  async login() {
    const { ctx, service } = this
    // 校验参数
    ctx.validate(this.UserLoginTransfer)
    // 组装参数
    const payload = ctx.request.body || {}
    // 调用 Service 进行业务处理
    const res = await service.userAccess.login(payload)
    // 设置响应内容和响应状态码
    ctx.helper.success({ctx, res})
  }

  // 用户登出
  async logout() {
    const { ctx, service } = this
    // 调用 Service 进行业务处理
    await service.userAccess.logout()
    // 设置响应内容和响应状态码
    ctx.helper.success({ctx, message: ctx.__('Log out')})
  }

  // 修改密码
  async updatePassword() {

    const { ctx, service } = this

    ctx.validate(this.UserUpdatePassword)

    const { userid } = ctx.user

    const { new_password, password } = ctx.request.body

    const userinfo = await service.user.show(userid)

    if(userinfo.userpwd!==ctx.helper.md5(password)) {
      ctx.throw(422, ctx.__('The original password is incorrect'))
    }

    const payload = {
      userpwd: ctx.helper.md5(new_password)
    }

    await service.user.update(userid, payload)

    // 设置响应内容和响应状态码
    ctx.helper.success({ctx, message: ctx.__('Modified successfully') })
  }

    // 用户信息
    async userinfo() {
      const { ctx, service } = this

      ctx.logger.info(ctx.user, 'userinfo')
  
      //const { userid } = ctx.user
  
     // const res = await service.user.show(userid)
  
      // 设置响应内容和响应状态码
      ctx.helper.success({ctx, res: { user: ctx.user } })
    }
  
}

module.exports = AuthController
